<!-- pages/index/index.vue -->
<template>
  <view class="container">
    <!-- 搜索区域 -->
    <view class="search-box">
      <uni-search-bar 
        v-model="searchValue" 
        placeholder="搜索题库" 
        @confirm="handleSearch"
        @input="handleSearchInput"
        radius="100"
        cancelButton="none"
      />
    </view>

    <!-- 搜索结果区域 -->
    <view v-if="showSearchResults" class="section">
      <view class="section-title">
        <text class="title-icon">▼</text>
        <text class="title-text">搜索结果</text>
        <text class="close-btn" @tap="closeSearchResults">×</text>
      </view>
      <view v-if="searchResults.length > 0" class="search-results">
        <view v-for="(item, index) in searchResults" 
              :key="index" 
              class="search-item"
              @tap="navigateToExam(item)">
          <text class="search-item-title">{{ item.title }}</text>
          <text class="search-item-desc">{{ item.description }}</text>
        </view>
      </view>
      <view v-else class="no-results">
        <text>没有找到相关题库</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
    </view>

    <!-- 公共课题库区域 -->
    <view v-if="!loading" class="section">
      <view class="section-title">
        <text class="title-icon">▼</text>
        <text class="title-text">公共课题库</text>
      </view>
      <view class="card-grid">
        <view v-for="(item, index) in commonCourses" 
              :key="index" 
              class="card" 
              :style="{ backgroundColor: item.bgColor }" 
              @tap="handleCard(item)">
          <view class="card-content">
            <text class="card-title">{{ item.title }}</text>
            <text class="card-desc">{{ item.desc }}</text>
          </view>
          <image :src="item.icon" mode="aspectFit" class="card-icon"></image>
        </view>
      </view>
    </view>

    <!-- 专业课题库区域 -->
    <view v-if="!loading" class="section">
      <view class="section-title">
        <text class="title-icon">▼</text>
        <text class="title-text">专业课题库</text>
      </view>
      <view class="card-grid">
        <view v-for="(item, index) in professionalCourses" 
              :key="index" 
              class="card" 
              :style="{ backgroundColor: item.bgColor }" 
              @tap="handleCard(item)">
          <view class="card-content">
            <text class="card-title">{{ item.title }}</text>
            <text class="card-desc">{{ item.desc }}</text>
          </view>
          <image :src="item.icon" mode="aspectFit" class="card-icon"></image>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { request } from '@/utils/request' // 假设你有一个封装好的请求工具

// 状态变量
const loading = ref(true)
const loadingText = {
  contentdown: '加载更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
}

// 搜索相关
const searchValue = ref('')
const searchResults = ref([])
const showSearchResults = ref(false)

// 题库数据
const commonCourses = ref([])
const professionalCourses = ref([])

// 初始化页面
onMounted(() => {
  fetchCategories()
})

// 获取题库分类
const fetchCategories = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/exam/categories',
      method: 'GET'
    })
    
    if (res.code === 200 && res.data) {
      commonCourses.value = res.data.commonCourses || []
      professionalCourses.value = res.data.professionalCourses || []
    } else {
      showErrorToast('获取题库分类失败')
    }
  } catch (error) {
    console.error('获取题库分类错误:', error)
    showErrorToast('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = async () => {
  if (!searchValue.value.trim()) {
    return
  }
  
  loading.value = true
  showSearchResults.value = true
  try {
    const res = await request({
      url: '/exam/search',
      method: 'GET',
      data: { keyword: searchValue.value }
    })
    
    if (res.code === 200) {
      searchResults.value = res.data || []
    } else {
      showErrorToast('搜索失败')
      searchResults.value = []
    }
  } catch (error) {
    console.error('搜索错误:', error)
    showErrorToast('网络错误，请稍后重试')
    searchResults.value = []
  } finally {
    loading.value = false
  }
}

const handleSearchInput = (e) => {
  searchValue.value = e
  if (!searchValue.value.trim()) {
    closeSearchResults()
  }
}

const closeSearchResults = () => {
  showSearchResults.value = false
  searchResults.value = []
}

// 卡片点击处理
const handleCard = (item) => {
  navigateToCategory(item.categoryId)
}

// 导航到分类详情页
const navigateToCategory = (categoryId) => {
  uni.navigateTo({
    url: `/pages/question-bank/category?categoryId=${categoryId}`
  })
}

// 导航到试卷详情页
const navigateToExam = (exam) => {
  uni.navigateTo({
    url: `/pages/question-bank/exam-detail?examId=${exam.id}`
  })
}

// 显示错误提示
const showErrorToast = (message) => {
  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })
}
</script>

<style>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-box {
  padding: 20rpx 0;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.section {
  margin-bottom: 30rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
  position: relative;
}

.title-icon {
  color: #333;
  margin-right: 10rpx;
  font-size: 24rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  position: absolute;
  right: 10rpx;
  font-size: 40rpx;
  color: #999;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.card {
  padding: 30rpx;
  border-radius: 12rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 160rpx;
}

.card-content {
  flex: 1;
  margin-right: 20rpx;
}

.card-title {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
}

.card-desc {
  color: rgba(255, 255, 255, 0.9);
  font-size: 24rpx;
  display: block;
}

.card-icon {
  width: 80rpx;
  height: 80rpx;
}

.loading {
  padding: 30rpx 0;
  text-align: center;
}

.search-results {
  margin-top: 10rpx;
}

.search-item {
  padding: 20rpx;
  border-bottom: 1px solid #eee;
}

.search-item-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.search-item-desc {
  font-size: 24rpx;
  color: #666;
  display: block;
}

.no-results {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>